//
//  ViewController.m
//  WLEmotionKeyBoard
//
//  Created by wanglei on 16/12/6.
//  Copyright © 2016年 wanglei. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.textView becomeFirstResponder];
    _textView.inputView = self.keyBoardView;
    
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(insetEmoticonText:) name:@"dianji" object:nil];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    if([self.textView isFirstResponder]){
        [self.textView resignFirstResponder];
    }else{
        [self.textView becomeFirstResponder];
    }
}

- (UIView *)keyBoardView{
    __weak  typeof(self) weakSelf = self;
    EmoticonKeyBoardView *KeyBoardView = [[EmoticonKeyBoardView alloc]initWithselectEmoticon];
    return KeyBoardView;
}

- (void)insetEmoticonText:(NSNotification *)notification{
//    http://www.jianshu.com/p/a2cb99dcd4fe 参数传递的相关解释
    NSDictionary *Em = [notification userInfo];
    Emoticon *em = [Em objectForKey:@"key"];
    NSLog(@"%@",em);
// 点击空白按钮
    if (em.isEmpty == true) {
        return;
    }
    if (em.isDelete == true) {
//        回删
        [_textView deleteBackward];
        return;
    }
//    点击emoji按钮
    if(em.code != nil){
        [_textView replaceRange:_textView.selectedTextRange withText:em.emojiStr];
        return;
    }
//    图片的显示
    NSTextAttachment *attachment = [[NSTextAttachment alloc]init];
//    1:将附件类型添加图片
    attachment.image = [UIImage imageWithContentsOfFile:em.imagePath];
    NSLog(@"em.imagePath = %@",em.imagePath);
//    1.1设置附件类型的bounds
    CGFloat lineHeight = _textView.font.lineHeight;
    attachment.bounds = CGRectMake(0, -4, lineHeight, lineHeight);
//   根据attachment创建属性字符串
//    http://www.jianshu.com/p/fcd3bc38ca3b
   NSAttributedString *str = [NSAttributedString attributedStringWithAttachment:attachment];
//    转换为可变的属性字符串
    NSMutableAttributedString *imageText = [[NSMutableAttributedString alloc]initWithAttributedString:str];
//   给文本添加属性,只有可变的文本才能添加属性
    [imageText addAttribute:NSFontAttributeName value:_textView.font range:NSMakeRange(0, 1)];
// 2 获取当前显示的文本属性文本
   NSMutableAttributedString *strM = [[NSMutableAttributedString alloc]initWithAttributedString:_textView.attributedText];
// 2.1 将选中的range 替换为属性字符串
//  2.1在修改之前先记录选中的光标a
    NSRange range = _textView.selectedRange;
    [strM replaceCharactersInRange:range withAttributedString:imageText];
    
// 3   设置属性字符川
    _textView.attributedText = strM;
// 4设置完毕后恢复光标
    _textView.selectedRange = NSMakeRange(range.location + 1, 0);
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
